#!/bin/bash 本地传输到远端jar包并使用docker-compose方式启动脚本

# 源文件路径
BOOT_SOURCE_PATTERN="./boot/target/boot-*.jar"
GATEWAY_SOURCE_PATTERN="./gateway/target/gateway-*.jar"
# 目标用户
TARGET_USER="agilerobots"
# 目标主机
TARGET_HOST="10.8.7.30"
# 目标路径
DOCKER_DIR="/home/agilerobots/docker/"
BOOT_TARGET_PATH="${DOCKER_DIR}java/boot"
GATEWAY_TARGET_PATH="${DOCKER_DIR}java/gateway"
# 目标脚本
TARGET_SCRIPT="${DOCKER_DIR}docker_compose_start.sh"
ENV_SCRIPT="${DOCKER_DIR}create_env_file.sh"

# 提示用户输入密码
read -s -p "Enter password for ${TARGET_USER}@${TARGET_HOST}: " PASSWORD
echo

# 传输文件函数
transfer_files() {
  local source_pattern=$1
  local target_path=$2
  matching_files=($(ls $source_pattern 2>/dev/null))
  if [ ${#matching_files[@]} -eq 0 ]; then
    echo "Error: No files found matching the pattern $source_pattern."
    exit 1
  fi

  for file in "${matching_files[@]}"; do
    if [ -f "$file" ]; then
      echo "Transferring $file..."
      sshpass -p "$PASSWORD" scp "$file" "${TARGET_USER}@${TARGET_HOST}:${target_path}"
      if [ $? -ne 0 ]; then
        echo "Error: Failed to transfer $file."
        exit 1
      fi
    else
      echo "Warning: $file is not a regular file, skipping."
    fi
  done
}

# 传输boot文件
transfer_files "$BOOT_SOURCE_PATTERN" "$BOOT_TARGET_PATH"
echo "boot transferred successfully."
transfer_files "$GATEWAY_SOURCE_PATTERN" "$GATEWAY_TARGET_PATH"
echo "gateway transferred successfully."

# 检查远程脚本是否存在
if ! sshpass -p "$PASSWORD" ssh ${TARGET_USER}@${TARGET_HOST} "[ -f ${TARGET_SCRIPT} ]"; then
  echo "Error: Remote script ${TARGET_SCRIPT} does not exist."
  exit 1
fi

# 执行远程脚本
echo "Starting remote script on ${TARGET_HOST}..."
sshpass -p "$PASSWORD" ssh ${TARGET_USER}@${TARGET_HOST} "bash ${ENV_SCRIPT}"
sshpass -p "$PASSWORD" ssh ${TARGET_USER}@${TARGET_HOST} "bash ${TARGET_SCRIPT}"

# 检查ssh命令是否成功
if [ $? -ne 0 ]; then
  echo "Error: Failed to execute remote script."
  exit 1
else
  echo "Remote script executed successfully."
fi